//
//  MPMainViewController_iPad.m
//  MissPaparazzi
//
//  Created by Alexey Aleshkov on 18.08.12.
//  Copyright (c) 2012 DzeTech. All rights reserved.
//


#import "MPMainViewController.h"
#import "FXLabel.h"
#import "FXLabel+MPNavigationBarTitle.h"
#import "UIGlossyButton.h"
#import "UIGlossyButton+MPNavigationBarTitle.h"
#import "GMGridViewLayoutStrategies.h"
#import "UIAlertView+Blocks.h"
#import "MPStore.h"
#import "MPMainViewOptionsController.h"
#import "MPGridViewCell.h"
#import "MPVideoViewController.h"
#import "MPAboutViewController.h"
#import "SVPullToRefresh.h"


@interface MPMainViewController () <MPMainViewOptionsControllerDelegate, NSFetchedResultsControllerDelegate, GMGridViewDataSource, MPGridViewCellDelegate>

@end


@implementation MPMainViewController

#pragma mark -
#pragma mark Init / Dealloc

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
	self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
	if (self) {
	}
	return self;
}

- (void)dealloc
{
	[_fetchResultsController release];
	[_progressHUD removeFromSuperview];
	[_progressHUD release];
	[_optionsPopoverController dismissPopoverAnimatd:NO];
	[_optionsPopoverController release];
    [_holePatternView release];
	[_gridView release];
    [_shadowView release];
	[super dealloc];
}

#pragma mark -
#pragma mark Overrides (Nib loading)

- (void)viewDidLoad
{
	[super viewDidLoad];

	if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) {
		_shadowInsets = UIEdgeInsetsMake(8, 5, 6, 5);
	} else {
		_shadowInsets = UIEdgeInsetsMake(30, 16, 14, 16);
	}
	
	NSString *titleViewLabelTitle = NSLocalizedString(@"MainView.NavigationItem.Title", @"");
	FXLabel *titleViewLabel = [[FXLabel alloc] init];
	[titleViewLabel setMPNavigationBarTitleStyle];
	titleViewLabel.numberOfLines = 1;
	titleViewLabel.text = titleViewLabelTitle;
	titleViewLabel.font = [UIFont boldSystemFontOfSize:16];
	titleViewLabel.frame = CGRectMake(0, 0, 140, 44);
	titleViewLabel.autoresizingMask = (UIViewAutoresizingFlexibleWidth);
	self.navigationItem.titleView = titleViewLabel;
	[titleViewLabel release];

	if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) {
		UIImage *optionsButtonImage = [UIImage imageNamed:@"MenuButton"];
		UIGlossyButton *leftBarOptionsButton = [[UIGlossyButton alloc] initWithFrame:CGRectMake(0, 0, 34, 32)];
		[leftBarOptionsButton addTarget:self action:@selector(optionsButtonTouchUpInsideAction:forEvent:) forControlEvents:UIControlEventTouchUpInside];
		[leftBarOptionsButton setImage:optionsButtonImage forState:UIControlStateNormal];
		[leftBarOptionsButton setMPNavigationBarTitleStyle];
		UIBarButtonItem *leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftBarOptionsButton];
		self.navigationItem.leftBarButtonItem = leftBarButtonItem;
		[leftBarButtonItem release];
		[leftBarOptionsButton release];

		UIImage *aboutUsButtonImage = [UIImage imageNamed:@"AboutButton"];
		UIGlossyButton *rightBarAboutUsButton = [[UIGlossyButton alloc] initWithFrame:CGRectMake(0, 0, 34, 32)];
		[rightBarAboutUsButton addTarget:self action:@selector(aboutButtonTouchUpInsideAction:) forControlEvents:UIControlEventTouchUpInside];
		[rightBarAboutUsButton setImage:aboutUsButtonImage forState:UIControlStateNormal];
		[rightBarAboutUsButton setMPNavigationBarTitleStyle];
		rightBarAboutUsButton.titleLabel.font = [UIFont boldSystemFontOfSize:20];
		UIBarButtonItem *rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightBarAboutUsButton];
		self.navigationItem.rightBarButtonItem = rightBarButtonItem;
		[rightBarButtonItem release];
		[rightBarAboutUsButton release];
	} else {
		const CGFloat kSeparatorLength = 8;

		UIView *leftBarView = [[UIView alloc] init];
		
		UIImage *aboutUsButtonImage = [UIImage imageNamed:@"AboutButton"];
		UIGlossyButton *leftBarAboutUsButton = [[UIGlossyButton alloc] initWithFrame:CGRectMake(0, 0, 34, 32)];
		[leftBarAboutUsButton addTarget:self action:@selector(aboutButtonTouchUpInsideAction:) forControlEvents:UIControlEventTouchUpInside];
		[leftBarAboutUsButton setImage:aboutUsButtonImage forState:UIControlStateNormal];
		[leftBarAboutUsButton setMPNavigationBarTitleStyle];
		leftBarAboutUsButton.titleLabel.font = [UIFont boldSystemFontOfSize:20];
		[leftBarView addSubview:leftBarAboutUsButton];
		[leftBarAboutUsButton release];
		
		UIImage *optionsButtonImage = [UIImage imageNamed:@"MenuButton"];
		UIGlossyButton *leftBarOptionsButton = [[UIGlossyButton alloc] initWithFrame:CGRectMake(34 + kSeparatorLength, 0, 34, 32)];
		[leftBarOptionsButton addTarget:self action:@selector(optionsButtonTouchUpInsideAction:forEvent:) forControlEvents:UIControlEventTouchUpInside];
		[leftBarOptionsButton setImage:optionsButtonImage forState:UIControlStateNormal];
		[leftBarOptionsButton setMPNavigationBarTitleStyle];
		[leftBarView addSubview:leftBarOptionsButton];
		[leftBarOptionsButton release];
		
		leftBarView.frame = CGRectMake(0, 0, 34 + kSeparatorLength + 34, 32);
		UIBarButtonItem *leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftBarView];
		self.navigationItem.leftBarButtonItem = leftBarButtonItem;
		[leftBarButtonItem release];
		[leftBarView release];
		
		UIImage *updateButtonImage = [UIImage imageNamed:@"ReloadButton"];
		NSString *refreshString = NSLocalizedString(@"MainView.NavigationItem.Refresh", nil);
		UIGlossyButton *rightBarUpdateButton = [[UIGlossyButton alloc] initWithFrame:CGRectMake(0, 0, 90, 32)];
		[rightBarUpdateButton addTarget:self action:@selector(updateButtonTouchUpInsideAction:) forControlEvents:UIControlEventTouchUpInside];
		[rightBarUpdateButton setTitle:refreshString forState:UIControlStateNormal];
		[rightBarUpdateButton setImageEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 4)];
		[rightBarUpdateButton setImage:updateButtonImage forState:UIControlStateNormal];
		[rightBarUpdateButton setMPNavigationBarTitleStyle];
		UIBarButtonItem *rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightBarUpdateButton];
		self.navigationItem.rightBarButtonItem = rightBarButtonItem;
		[rightBarButtonItem release];
		[rightBarUpdateButton release];
	}
	
	_holePatternView.patternImage = [UIImage imageNamed:@"Pattern"];
	_holePatternView.fillColor = [UIColor colorWithWhite:0 alpha:0.16];
	_holePatternView.holeInsets = _shadowInsets;
	_holePatternView.holeRadius = 6;
	_shadowView.shadowBlur = 12;
	_shadowView.shadowInsets = _holePatternView.holeInsets;
	_shadowView.shadowRadius = _holePatternView.holeRadius;
	
	_progressHUD = [[MBProgressHUD alloc] initWithView:self.navigationController.view];
	_progressHUD.removeFromSuperViewOnHide = NO;
	// HACK!!! Add to navigationController.view.window, not to navigationController.view. It cause a rotation bug. View lays under navigation bar.
	[self.navigationController.view.window addSubview:_progressHUD];
	
	
	MPMainViewOptionsController *viewController = [[MPMainViewOptionsController alloc] initWithNibName:@"MPMainViewOptionsController" bundle:nil];
	viewController.delegate = self;
	_optionsPopoverController = [[TSPopoverController alloc] initWithContentViewController:viewController];
	_optionsPopoverController.cornerRadius = 5;
	_optionsPopoverController.popoverBaseColor = [UIColor lightGrayColor];
	_optionsPopoverController.popoverGradient = NO;
	_optionsPopoverController.arrowPosition = TSPopoverArrowPositionVertical;
	_optionsPopoverController.popoverBaseColor = [UIColor blackColor];
	
	NSString *buyAllProductPrice = [MPStore sharedInstance].buyAllProductPrice;
	if ([buyAllProductPrice length]) {
		NSString *buyAllFormat = NSLocalizedString(@"MainView.NavigationItem.BuyAllFormat", nil);
		NSString *buyAllString = [NSString stringWithFormat:buyAllFormat, buyAllProductPrice];
		[((MPMainViewOptionsController *)_optionsPopoverController.contentViewController).buyAllButton setTitle:buyAllString forState:UIControlStateNormal];
	} else {
		NSString *buyAllString = NSLocalizedString(@"MainView.NavigationItem.BuyAll", nil);
		[((MPMainViewOptionsController *)_optionsPopoverController.contentViewController).buyAllButton setTitle:buyAllString forState:UIControlStateNormal];
	}
	
	[viewController release];
	

	MPStore *store = [MPStore sharedInstance];
	NSManagedObjectContext *managedObjectContext = store.managedObjectContext;
	
	NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"Episode"];
	NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"productID" ascending:YES];
	NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
	fetchRequest.sortDescriptors = sortDescriptors;
	
	_fetchResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:managedObjectContext sectionNameKeyPath:nil cacheName:@"Root"];
	_fetchResultsController.delegate = self;
	NSError *error = nil;
	if (![_fetchResultsController performFetch:&error]) {
		NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
	}
	
	//NSArray *array = [managedObjectContext executeFetchRequest:fetchRequest error:nil];
	//[MPEpisode coreDataDescriptionForArray:array];

	
	_gridView.style = GMGridViewStylePush;
	_gridView.itemSpacing = 0;
	_gridView.centerGrid = YES;
	if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) {
		_gridView.minEdgeInsets = UIEdgeInsetsMake(8, 0, 8, 0);
		[_gridView addPullToRefreshWithActionHandler:^{
			if (_gridView.pullToRefreshView.state == SVPullToRefreshStateLoading) {
				[self updateItemsShowingHUD:NO];
			}
		}];
		_gridView.pullToRefreshView.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhite;
		_gridView.pullToRefreshView.arrowColor = [UIColor colorWithRed:238/255.0 green:224/225.0 blue:225/255.0 alpha:1];
		_gridView.pullToRefreshView.textColor = _gridView.pullToRefreshView.arrowColor;

		_gridView.minEdgeInsets = UIEdgeInsetsMake(0, 18, 0, 18);
		_gridView.layoutStrategy = [GMGridViewLayoutStrategyFactory strategyFromType:GMGridViewLayoutVertical];
	} else {
		_gridView.minEdgeInsets = UIEdgeInsetsZero;
		_gridView.layoutStrategy = [GMGridViewLayoutStrategyFactory strategyFromType:GMGridViewLayoutHorizontal];
	}
	_gridView.dataSource = self;
	
	NSFetchRequest *fetchCountRequest = [NSFetchRequest fetchRequestWithEntityName:@"Episode"];
	fetchCountRequest.includesSubentities = NO;
	NSUInteger count = [managedObjectContext countForFetchRequest:fetchCountRequest error:&error];
	if (count == NSNotFound || count == 0) {
		[self updateItemsShowingHUD:YES];
	}
}

- (void)viewDidUnload
{
	[_fetchResultsController release];
	_fetchResultsController = nil;
	[_progressHUD removeFromSuperview];
	[_progressHUD release];
    _progressHUD = nil;
	[_optionsPopoverController dismissPopoverAnimatd:NO];
	[_optionsPopoverController release];
    _optionsPopoverController = nil;
    [_holePatternView release];
    _holePatternView = nil;
	[_gridView release];
	_gridView = nil;
    [_shadowView release];
    _shadowView = nil;
	[super viewDidUnload];
}

- (void)viewWillAppear:(BOOL)animated
{
	[super viewWillAppear:animated];
	
	[self willRotateToInterfaceOrientation:self.interfaceOrientation duration:0];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
	BOOL result;
	if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) {
		result = (UIInterfaceOrientationPortrait == interfaceOrientation);
	} else {
		result = YES;
	}

	return result;
}

- (BOOL)shouldAutorotate
{
	if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) {
		return NO;
	} else {
		return YES;
	}
}

- (NSUInteger)supportedInterfaceOrientations
{
	if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) {
		return UIInterfaceOrientationMaskPortrait;
	} else {
		return UIInterfaceOrientationMaskAll;
	}
}

- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation
{
	return UIInterfaceOrientationPortrait;
}

- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
	[super willRotateToInterfaceOrientation:toInterfaceOrientation duration:duration];

	if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) {
	} else {
		if (UIInterfaceOrientationIsLandscape(toInterfaceOrientation)) {
			_gridView.layoutStrategy = [GMGridViewLayoutStrategyFactory strategyFromType:GMGridViewLayoutHorizontal];
		} else {
			_gridView.layoutStrategy = [GMGridViewLayoutStrategyFactory strategyFromType:GMGridViewLayoutVertical];
		}
		
		CGRect bounds;
		bounds = self.view.bounds;
		bounds = CGRectInset(bounds, (_shadowInsets.left + 1 + _shadowInsets.right + 1) / 2, (_shadowInsets.top + 1 + _shadowInsets.bottom + 1) / 2);
		bounds.origin.x = _shadowInsets.left + 1;
		bounds.origin.y = _shadowInsets.top + 1;
		_gridView.superview.frame = bounds;
		// HACK: two upper cells displays with offset
		[_gridView reloadData];
	}
}

#pragma mark -
#pragma mark NSFetchedResultsControllerDelegate

- (void)controllerWillChangeContent:(NSFetchedResultsController *)controller
{
	//[_gridView beginUpdates];
}

- (void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type newIndexPath:(NSIndexPath *)newIndexPath
{
//	switch (type) {
//		case NSFetchedResultsChangeInsert:
//			[_gridView insertObjectAtIndex:newIndexPath.row withAnimation:GMGridViewItemAnimationFade];
//			break;
//			
//		case NSFetchedResultsChangeDelete:
//			[_gridView removeObjectAtIndex:indexPath.row withAnimation:GMGridViewItemAnimationFade];
//			break;
//			
//		case NSFetchedResultsChangeUpdate:
//			[_gridView reloadObjectAtIndex:indexPath.row withAnimation:GMGridViewItemAnimationFade];
//			break;
//			
//		case NSFetchedResultsChangeMove:
//			[_gridView swapObjectAtIndex:indexPath.row withObjectAtIndex:newIndexPath.row animated:GMGridViewItemAnimationFade];
//			break;
//	}
}

- (void)controller:(NSFetchedResultsController *)controller didChangeSection:(id<NSFetchedResultsSectionInfo>)sectionInfo atIndex:(NSUInteger)sectionIndex forChangeType:(NSFetchedResultsChangeType)type
{
//	switch (type) {
//		case NSFetchedResultsChangeInsert:
//			[self.tableView insertSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationFade];
//			break;
//			
//		case NSFetchedResultsChangeDelete:
//			[self.tableView deleteSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationFade];
//			break;
//	}
}

- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller
{
	[_gridView reloadData];
}

#pragma mark -
#pragma mark GMGridViewDataSource

- (NSInteger)numberOfItemsInGMGridView:(GMGridView *)gridView
{
	NSInteger result = 0;
	
    if ([[_fetchResultsController sections] count]) {
        id<NSFetchedResultsSectionInfo> sectionInfo = [[_fetchResultsController sections] objectAtIndex:0];
        result = [sectionInfo numberOfObjects];
    }
    
	return result;
}

- (CGSize)GMGridView:(GMGridView *)gridView sizeForItemsInInterfaceOrientation:(UIInterfaceOrientation)orientation
{
	//NSAssert(UIInterfaceOrientationIsLandscape(orientation), @"");
	CGSize result;
	if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) {
		result = CGSizeMake(256, 216);
	} else {
		result = CGSizeMake(332, 313);
	}
	return result;
}

- (GMGridViewCell *)GMGridView:(GMGridView *)gridView cellForItemAtIndex:(NSInteger)index
{
	static NSString *const kCellId = @"Cell";
	NSString *cellId = kCellId;
	
	GMGridViewCell *cell = [gridView dequeueReusableCellWithIdentifier:cellId];
	if (!cell) {
		CGSize size = [self GMGridView:gridView sizeForItemsInInterfaceOrientation:[[UIApplication sharedApplication] statusBarOrientation]];
		
		cell = [[GMGridViewCell alloc] initWithFrame:CGRectMake(0, 0, size.width, size.height)];
		[cell autorelease];
		cell.reuseIdentifier = cellId;
		
		NSString *nibName;
		if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) {
			nibName = @"MPGridViewCell_iPhone";
		} else {
			nibName = @"MPGridViewCell_iPad";
		}
		NSArray *objects = [[NSBundle mainBundle] loadNibNamed:nibName owner:nil options:nil];
		MPGridViewCell *contentView = [objects objectAtIndex:0];
		cell.contentView = contentView;
	}
	
	NSIndexPath *indexPath = [NSIndexPath indexPathForRow:index inSection:0];
	MPEpisode *item = (MPEpisode *)[_fetchResultsController objectAtIndexPath:indexPath];
	MPGridViewCell *contentView = (MPGridViewCell *)cell.contentView;
	contentView.delegate = self;
	contentView.data = item;
	
	return cell;
}

- (BOOL)GMGridView:(GMGridView *)gridView canDeleteItemAtIndex:(NSInteger)index
{
	return NO;
}

#pragma mark -
#pragma mark MPGridViewCellDelegate

- (void)MPGridViewCell:(MPGridViewCell *)cell buy:(MPEpisode *)object
{
	NSLog(@"%@", NSStringFromSelector(_cmd));
	
	MPStoreSuccessBlock successBlock = ^{
		[self MPGridViewCell:cell download:object];
	};
	MPStoreFailureBlock failureBlock = ^(NSError *error) {
		[UIAlertView showWithTitle:@"Error" message:error.localizedDescription cancelBlock:nil dismissBlock:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
	};
	[[MPStore sharedInstance] purchaseItem:object successBlock:successBlock failureBlock:failureBlock];
}

- (void)MPGridViewCell:(MPGridViewCell *)cell open:(MPEpisode *)object
{
	NSLog(@"%@", NSStringFromSelector(_cmd));
	
	NSString *nibName;
	if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) {
		nibName = @"MPVideoViewController_iPhone";
	} else {
		nibName = @"MPVideoViewController_iPad";
	}
	MPVideoViewController *viewController = [[MPVideoViewController alloc] initWithNibName:nibName bundle:nil];
	viewController.data = object;
	[self.navigationController pushViewController:viewController animated:YES];
	[viewController release];
}

- (void)MPGridViewCell:(MPGridViewCell *)cell download:(MPEpisode *)object
{
	NSLog(@"%@", NSStringFromSelector(_cmd));
	
	MPStoreSuccessBlock successBlock = ^{
	};
	MPStoreFailureBlock failureBlock = ^(NSError *error) {
		NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
		[UIAlertView showWithTitle:@"Error" message:error.localizedDescription cancelBlock:nil dismissBlock:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
	};
	[[MPStore sharedInstance] downloadItem:object successBlock:successBlock failureBlock:failureBlock];
}

- (void)MPGridViewCell:(MPGridViewCell *)cell cancelDownloading:(MPEpisode *)object
{
	NSLog(@"%@", NSStringFromSelector(_cmd));
	
	UIAlertViewDismissBlock dismissBlock = ^(NSInteger buttonIndex) {
		if (buttonIndex == 1) {
			[[MPStore sharedInstance] cancelDownloadingItem:object];
		}
        NSLog(@"dismissBlock %@", NSStringFromSelector(_cmd));
	};

	[UIAlertView showWithTitle:@"Cancel" message:@"Are you sure you want to cancel the download?" cancelBlock:nil dismissBlock:dismissBlock cancelButtonTitle:@"No" otherButtonTitles:@"Yes", nil];
}

- (void)MPGridViewCell:(MPGridViewCell *)cell remove:(MPEpisode *)object
{
	NSLog(@"%@", NSStringFromSelector(_cmd));
	
	UIAlertViewDismissBlock dismissBlock = ^(NSInteger buttonIndex) {
		if (buttonIndex == 1) {
			[[MPStore sharedInstance] removeItem:object];
		}
	};
	[UIAlertView showWithTitle:@"Cancel" message:@"Are you sure you want to delete episode?" cancelBlock:nil dismissBlock:dismissBlock cancelButtonTitle:@"No" otherButtonTitles:@"Yes", nil];
}

#pragma mark -
#pragma mark Private methods

- (void)updateItemsShowingHUD:(BOOL)showHUD
{
	MPStoreSuccessBlock successBlock = ^{
		NSString *buyAllFormat = NSLocalizedString(@"MainView.NavigationItem.BuyAllFormat", nil);
		NSString *buyAllProductPrice = [MPStore sharedInstance].buyAllProductPrice;
		NSString *buyAllString = [NSString stringWithFormat:buyAllFormat, buyAllProductPrice];
		[((MPMainViewOptionsController *)_optionsPopoverController.contentViewController).buyAllButton setTitle:buyAllString forState:UIControlStateNormal];
		if (showHUD) {
			[_progressHUD hide:YES];
		} else if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) {
			[_gridView.pullToRefreshView stopAnimating];
		}
	};
	MPStoreFailureBlock failureBlock = ^(NSError *error) {
		NSString *buyAllString = NSLocalizedString(@"MainView.NavigationItem.BuyAll", nil);
		[((MPMainViewOptionsController *)_optionsPopoverController.contentViewController).buyAllButton setTitle:buyAllString forState:UIControlStateNormal];
		if (showHUD) {
			[_progressHUD hide:YES];
		} else if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) {
			[_gridView.pullToRefreshView stopAnimating];
		}
		[UIAlertView showWithTitle:@"Error" message:error.localizedDescription cancelBlock:nil dismissBlock:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
	};
	_progressHUD.dimBackground = YES;
	_progressHUD.mode = MBProgressHUDModeIndeterminate;
	_progressHUD.labelText = NSLocalizedString(@"MainView.UpdatingEpisodes", nil);
	if (showHUD) {
		[_progressHUD show:YES];
	}
	[[MPStore sharedInstance] updateWithSuccessBlock:successBlock failureBlock:failureBlock];
}

#pragma mark -
#pragma mark Actions

- (IBAction)aboutButtonTouchUpInsideAction:(id)sender
{
	NSString *nibName;
	if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) {
		nibName = @"MPAboutViewController_iPhone";
	} else {
		nibName = @"MPAboutViewController_iPad";
	}
	MPAboutViewController *viewController = [[MPAboutViewController alloc] initWithNibName:nibName bundle:nil];
	[self.navigationController pushViewController:viewController animated:YES];
	[viewController release];
}

- (void)optionsButtonTouchUpInsideAction:(id)sender forEvent:(UIEvent *)event
{
	[_optionsPopoverController showPopoverWithTouch:event];
	//[_optionsPopoverController presentPopoverFromRect:CGRectMake(68, -8, 4, 4) inView:self.view permittedArrowDirections:UIPopoverArrowDirectionUp animated:YES];
}

- (void)updateButtonTouchUpInsideAction:(id)sender
{
	NSLog(@"%@", NSStringFromSelector(_cmd));
	
	[self updateItemsShowingHUD:YES];
}

- (void)restorePurchasesButtonTouchUpInsideAction:(id)sender
{
	NSLog(@"%@", NSStringFromSelector(_cmd));
	
	[_optionsPopoverController dismissPopoverAnimatd:YES];

	MPStoreSuccessBlock successBlock = ^{
		[_progressHUD hide:YES];
	};
	MPStoreFailureBlock failureBlock = ^(NSError *error) {
		[_progressHUD hide:YES];
		[UIAlertView showWithTitle:@"Error" message:error.localizedDescription cancelBlock:nil dismissBlock:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
	};
	_progressHUD.dimBackground = YES;
	_progressHUD.mode = MBProgressHUDModeIndeterminate;
	_progressHUD.labelText = NSLocalizedString(@"MainView.RestoringPurchases", nil);
	[_progressHUD show:YES];
	[[MPStore sharedInstance] restorePurchasesWithSuccessBlock:successBlock failureBlock:failureBlock];
}

- (void)buyAllButtonTouchUpInsideAction:(id)sender
{
	NSLog(@"%@", NSStringFromSelector(_cmd));
	
	[_optionsPopoverController dismissPopoverAnimatd:YES];
	
	MPStoreSuccessBlock successBlock = ^{
	};
	MPStoreFailureBlock failureBlock = ^(NSError *error) {
		[UIAlertView showWithTitle:@"Error" message:error.localizedDescription cancelBlock:nil dismissBlock:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
	};
	[[MPStore sharedInstance] purchaseAllItemsWithSuccessBlock:successBlock failureBlock:failureBlock];
}

@end
